/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hk.ces.pos.filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 *
 * @author Silence
 */
public class FilterLogon implements Filter
{

  private String config;
  private String logonURL;
  Logger logger = Logger.getLogger("FilterLogon");

  public void destroy()
  {
    this.config = null;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  {

    HttpServletRequest req;
    req = (HttpServletRequest) request;
    String URLString = req.getRequestURI();
    HttpServletResponse res;
    res = (HttpServletResponse) response;

    req.setCharacterEncoding(config);
    res.setCharacterEncoding(config);
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("Cache-Control", "no-store");
    res.setDateHeader("Expires", 0);
    res.setHeader("Pragma", "no-cache");
    HttpSession httpSession = req.getSession();
    //System.out.println(httpSession.getAttribute("userType") == null);
    if (httpSession.getAttribute("userType") == null)
    {
      if (URLString.contains("logon.do"))
      {
        chain.doFilter(request, response);
      }
      else
      {
        req.getRequestDispatcher(logonURL).forward(req, res);
      }
    }
    else
    {
      chain.doFilter(request, response);
    }
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException
  {
    this.config = filterConfig.getInitParameter("chars");
    this.logonURL = filterConfig.getInitParameter("logonURL");
  }
}
